/**
 * @Author: wangjian
 * 656876071@qq.com
 * @Date: 2024-08-02 18:29:37
 * @LastEditTime: 2024-09-09 23:28:21
 * @FilePath: src/core/common/hooks/FormHooks.ts
 * @Description:
 */

import {ref, type Ref} from "vue";
import type {Ret} from "@/core/utils/request";
import {message} from "ant-design-vue";

export const SIMPLE_FORM_SUBMIT_KEY = "submitCallback" 

export const useSimpleForm = (form: Ref<any>, primaryKey: string, addApi: Function, updateApi: Function, getByIdApi: Function,callback:Function) => {
    const modalIsSubmitting = ref(false)
    const modalIsVisible = ref(false)

    // 录入、更新
    const onSubmit = () => {
        modalIsSubmitting.value = true
        console.debug("SimpleForm;Form:", form.value)
        if (!form.value[primaryKey]) {
            return addApi(form.value).then((res: any | Ret) => {
                console.debug("SimpleForm;Result:", res)
                if (res.code == 0) {
                    message.success('添加成功')
                } else {
                    message.error(res.data)
                }
                return res
            })
        } else {
            return updateApi(form.value).then((res: any | Ret) => {
                console.debug("SimpleForm;Result:", res)
                if (res.code == 0) {
                    message.success('修改成功')
                } else {
                    message.error(res.data)
                }
                return res
            })

        }
    }

    
    /**
     *
     */
    const modalSubmit = () => {
        onSubmit().then((res: any | Ret) => {
            if (res.code == 0)
                setTimeout(() => {
                    modalIsVisible.value = false
                    callback(SIMPLE_FORM_SUBMIT_KEY)
                    modalIsSubmitting.value = false
                }, 1000)
            else
                modalIsSubmitting.value = false
        }).catch((err: any) => {
            console.debug(err)
            message.error("提交失败")
            modalIsSubmitting.value = false
        })
    }
    const showAddForm = () => {
        modalIsVisible.value = true
        form.value = {}
    }
    const showEditForm = (id: string) => {
        return getByIdApi(id).then((res: any | Ret) => {
            form.value = res.data
            modalIsVisible.value = true
            return res.data
        }).catch((err: any) => {
            message.error("查询基本信息失败")
        })
    }

    return {
        showAddForm,
        showEditForm,
        modalIsVisible,
        modalIsSubmitting,
        modalSubmit,
    }
}